import {
  copyComponent,
  deleteComponent,
  pasteComponent,
  selectNextComponent,
  selectPrevComponent,
} from "@/store/componentsReducer";
import { useKeyPress } from "ahooks";
import { useDispatch } from "react-redux";
import { ActionCreators } from "redux-undo";

/**
 * 判断 activeElement 是否合法
 * @returns
 */
const isActiveElementValid = () => {
  const activeElement = document.activeElement;

  if (activeElement === document.body) {
    return true;
  }

  // 判断 dnd-kit
  if (activeElement?.matches('div[role="button"]')) return true;

  return false;
};

const useBindCanvasKeyPress = () => {
  const dispatch = useDispatch();

  useKeyPress(["backspace", "delete"], () => {
    if (!isActiveElementValid()) return;

    dispatch(deleteComponent());
  });

  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementValid()) return;

    dispatch(copyComponent());
  });

  useKeyPress(["ctrl.v", "meta.c"], () => {
    if (!isActiveElementValid()) return;

    dispatch(pasteComponent());
  });

  // 选中上一个
  useKeyPress("uparrow", () => {
    if (!isActiveElementValid()) return;

    dispatch(selectPrevComponent());
  });

  useKeyPress("downarrow", () => {
    if (!isActiveElementValid()) return;

    dispatch(selectNextComponent());
  });

  // 撤销重做
  useKeyPress(
    ["ctrl.z", "meta.z"],
    () => {
      dispatch(ActionCreators.undo());
    },
    {
      exactMatch: true,
    }
  );

  useKeyPress(
    ["ctrl.shift.z", "meta.shift.z"],
    () => {
      dispatch(ActionCreators.redo());
    },
    {
      exactMatch: true,
    }
  );
};

export default useBindCanvasKeyPress;
